package com.faner.fast.validator.impl;

import com.faner.fast.validator.EnumValue;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 枚举校验器
 *
 */
@Slf4j
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    /**
     * 枚举类
     */
    private Class<? extends Enum<?>> cls;
    private String enumMethod;


    @Override
    public void initialize(EnumValue constraintAnnotation) {
        cls = constraintAnnotation.target();
        enumMethod = constraintAnnotation.enumMethod();
    }

    /**
     * 校验
     *
     * @param value   传入值
     * @param context 上下文
     * @return 是否成功
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        try {
            Object[] objs = cls.getEnumConstants();
            Method method = cls.getMethod(enumMethod);
            //必须是静态方法
//            if(!Modifier.isStatic(method.getModifiers())) {
//                throw new RuntimeException(String.format("%s method is not static method in the %s class", enumMethod, enumClass));
//            }
            for (Object obj : objs) {
                Object val = method.invoke(obj);
                if (val.equals(value)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            log.warn("EnumValue 校验异常", e);
            return false;
        }
    }
}
